package com.assessment.service.impl;

import com.assessment.entity.Aitemavg;
import com.assessment.entity.Ascore;
import com.assessment.entity.Column;
import com.assessment.mapper.AitemavgMapper;
import com.assessment.service.AitemavgService;
import com.assessment.service.AscoreService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static com.assessment.utils.Constant.SUBMIT;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 鑫十一
 * @since 2021-12-15
 */
@Service
@Transactional
public class AitemavgServiceImpl extends ServiceImpl<AitemavgMapper, Aitemavg> implements AitemavgService {

    private static final Logger log1 = LoggerFactory.getLogger(AitemavgServiceImpl.class);
    @Autowired(required = false)
    private AscoreService ascoreService;

    @Override
    public List<Column> getColumns() {
        List<Column> columns = new ArrayList<>();
        columns.add(new Column().setLabel("考核").setProp("aname"));
        columns.add(new Column().setLabel("考核项").setProp("itname"));
        columns.add(new Column().setLabel("考核对象").setProp("pname"));
        columns.add(new Column().setLabel("平均分").setProp("score"));
        return columns;
    }
    @Override
    public void computeAvg(){
        DecimalFormat df = new DecimalFormat("#.00");
        // 计算被评人的平均分
        QueryWrapper<Ascore> ascoreQueryWrapper = new QueryWrapper<>();
        ascoreQueryWrapper.select("DISTINCT itid");
        ascoreQueryWrapper.eq("status",SUBMIT);

        // 获取所有的打分项
        List<Ascore> list = ascoreService.list(ascoreQueryWrapper);
        list.forEach(itid->{
            // Ascore itid = list.get(1);
            log1.info("当前打分项:{}", itid);
            // 计算每个部门每个评分项多少分
            QueryWrapper<Ascore> queryWrapper = new QueryWrapper<>();
            // queryWrapper.select("DISTINCT bpid");
            queryWrapper.eq("itid",itid.getItid());
            queryWrapper.eq("status",SUBMIT);
            queryWrapper.ne("score","无");
            queryWrapper.orderByAsc("bpid");
            List<Ascore> list2 = ascoreService.list(queryWrapper);
            // 统计所有分数求平均值
            final String[] pid = {"pid","aid","itid"};
            final double[] aDouble = {(double) 0};
            final int[] num = {0};
            for (int i = 0; i < list2.size(); i++) {
                Ascore ascore = list2.get(i);
                log1.info("打分信息{}-{}-{}-{}",ascore.getItname(), ascore.getBpname(),ascore.getApname(), ascore.getScore());
                if (i == 0){
                    pid[0] = ascore.getBpid();
                    pid[1] = ascore.getAid();
                    pid[2] = ascore.getItid();
                }
                log1.info("combpname={}", pid[0]);
                log1.info("总分={}", aDouble[0]);
                log1.info("数量={}", num[0]);
                if(!pid[0].equals(ascore.getBpid())){
                    // 下一个了
                    double avg = num[0] != 0?(aDouble[0] / num[0]):0;
                    log1.info("平均分{}", avg);
                    QueryWrapper<Aitemavg> aitemavgQueryWrapper = new QueryWrapper<>();
                    aitemavgQueryWrapper.eq("aid", pid[1]);
                    aitemavgQueryWrapper.eq("itid", pid[2]);
                    aitemavgQueryWrapper.eq("pid", pid[0]);
                    List<Aitemavg> aitemavgs = this.list(aitemavgQueryWrapper);
                    log1.info("更新信息{}", aitemavgs.get(0).setScore(df.format(avg)));
                    this.updateById(aitemavgs.get(0).setScore(df.format(avg)));
                    pid[0] = ascore.getBpid();
                    pid[1] = ascore.getAid();
                    pid[2] = ascore.getItid();
                    num[0] = 0;
                    aDouble[0] = 0;
                }
                log1.info("更新分数=============");
                num[0] = num[0] + 1;
                double v = "无".equals(ascore.getScore()) ? 0.0 : Double.parseDouble(ascore.getScore());
                log1.info("总分{}", v);
                aDouble[0] = aDouble[0] +  v;
            }
            if (num[0] != 0){
                double avg = num[0] != 0?(aDouble[0] / num[0]):0;
                log1.info("平均分{}", avg);
                QueryWrapper<Aitemavg> aitemavgQueryWrapper = new QueryWrapper<>();
                aitemavgQueryWrapper.eq("aid", pid[1]);
                aitemavgQueryWrapper.eq("itid", pid[2]);
                aitemavgQueryWrapper.eq("pid", pid[0]);
                List<Aitemavg> aitemavgs = this.list(aitemavgQueryWrapper);
                log1.info("更新信息{}", aitemavgs.get(0).setScore(df.format(avg)));
                this.updateById(aitemavgs.get(0).setScore(df.format(avg)));
            }
        });
    }
    @Override
    public List<Aitemavg> getAvglist(QueryWrapper<Aitemavg> queryWrapper) {
        computeAvg();
        return this.list(queryWrapper);
    }
}
